<?php

class ShareService extends AbstractService
{

    /**
     * @var ShareService
     */
    private static $instance;

    /**
     * Get the instance of ShareService.
     *
     * @return ShareService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new ShareService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理创建时的逻辑
     *
     * @param int $shardId
     * @return void
     */
    public function handleCreate($shardId)
    {

    }

    /**
     * 处理用户登录时的逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {
        if (GameService::get()->isDailyFirstLogin($userId)) {
            UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_DAILY_SHARE_TIMES, []);
        }
        $this->dailyClear($userId, GameService::get()->getReqTime());
    }

    /**
     * 处理用户登录时的逻辑
     *
     * @param int $userId
     * @return array(ShareVoList)
     */
    public function info($userId)
    {
        $shareList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SHARE);
        return [$shareList];
    }

    /**
     * 分享
     * @param $userId
     * @param $shareCode
     * @param $reqTime
     * @param $moduleId
     * @param $subId
     * @return bool
     */
    public function send($userId, $shareCode, $reqTime, $moduleId, $subId)
    {
        /**
         * @var $shareList ShareVoList
         * @var $share ShareVo
         */
        list($openId, $shareUserId, $inviteId, $shareId, $timestemp, $isAward, $param) = explode('^', $shareCode);
        $ikebanaId = null;
        if ($param) {
            list($type) = explode('|',$param);
            switch ($type) {
                case 1:
                    if ($shareId == GameConst::CULTIVATE_SHARE_ID) {
                        $shareCode = $shareId;
                    }
                    break;
                case 2:
                    break;
                case 3:
                    list(,$ikebanaId) =  explode('|',$param);
                    $ikebanaVaseConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_ARRANGEMENT_ONE, $ikebanaId, true);
                    if (!$ikebanaVaseConfig) {
                        return false;
                    }
                    break;
                default:
                    throw new SzException(29005);
            }

        }
        $shareList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SHARE);

        $share = $shareList->getElement($shareCode, false);
        $shareConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SHARE, $shareId, true);
        if ($share && $shareId != GameConst::CULTIVATE_SHARE_ID) {
            //重复的分享
            return true;
        }
        if ($share && $shareId == GameConst::CULTIVATE_SHARE_ID) {
            $shareIsExpire = $this->shareIsExpire($shareConfig,$share,$reqTime);
            if($shareIsExpire) {
                $share->setTouchUsers(array());
                $share->setShareTime($reqTime);
                $share->setIsGetReward(0);
                $share->setCultivateTouchUsers(array());
            }
        } else {
            $share = new ShareVo($userId, $shareCode, $shareId, json_encode([]), $reqTime, 0, json_encode([]), true);
        }

        $dailyShellTimes = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_DAILY_SHARE_TIMES);
        $todayShareCount = isset($dailyShellTimes[$shareId]) ? $dailyShellTimes[$shareId] : 0;

        $tid = '';
        if (!is_null($ikebanaId)) {
            $ikebanaIds = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_IKEBANA_IDS);
            if (in_array($ikebanaId,$ikebanaIds)) {
                $ikebanaId = null;
            }
        }

        if ($isAward || !is_null($ikebanaId)) {
            if (-1 != $shareConfig['fx_success1Times'] && $todayShareCount < $shareConfig['fx_success1Times']) {
                foreach ($shareConfig['fx_success1'] as $entityId => $count) {
                    GameService::get()->handleEntity($userId, $entityId, $count, true, true);
                    $tid .= $entityId . ':' . $count . '|';
                }
            }
        }

        if (!is_null($ikebanaId)) {
            $ikebanaIds[] = $ikebanaId;
            UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_IKEBANA_IDS, $ikebanaIds);
        }

        $shareTimes = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_DAILY_SHARE_TIMES);
        $shareTimes[$shareId] += 1;
        UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_DAILY_SHARE_TIMES, $shareTimes);
        if ($share->isInsert()) {
            $shareList->addElement($share);
            $shareList->setElement($shareCode, $share);
        } else {
            $shareList->updateElement($shareCode, $share);
        }

        SzPersister::get()->setVoList($shareList);

        // 更新任务进度---分享
        MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_SHARE, GameConst::ENTITY_TYPE_NULL, GameConst::ENTITY_PADDING_NULL, 1);

        switch ($moduleId) {
            case 1:
                $module = 'cultivate';
                $shareId = $subId . '&' . $shareId;
                break;
            case 2:
                $module = 'discolour';
                $shareId = $subId . '&' . $shareId;
                break;
            case 3:
                $module = 'mix';
                break;
            case 4:
                $module = 'order';
                break;
            case 5:
                $module = 'book';
                $shareId = $subId . '&' . $shareId;
                break;
            case 6:
                $module = 'lottery';
                break;
            case 7:
                $module = 'invite';
                break;
            case 8:
                $module = 'valentine';
                break;
            case 9:
                $module = 'ikebanaId';
                $shareId = $ikebanaId;
                break;
            case 10:
                $module = 'new_gift';
                break;
            case 12:
                $module = 'wanba_share';
                break;
            default:
                return true;
        }

        NewTaskService::get()->updateDailyTask($userId,GameConst::DAILY_TASK_SHARE,1);

        // 数据采集:分享
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:' . $module . '|action:share|',
                'item' => $shareId,
                'value' => 1
            )
        ));

        if ($tid) {
            CommonFunctionService::get()->reportResourceUseDetails(99999974,$userId,1,$tid,'send');//获得资源上报
            // 数据采集:分享产出
            StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
                'clientData' => array(
                    'tid' => $tid,
                    'item' => $module . '_share&' . $shareId,
                )
            ));
        }
        return true;
    }

    /**
     * 点击链接
     * @param int $touchUser
     * @param string $shareCode
     * @param int $reqTime
     * @throws SzException
     * @return bool
     */
    public function touch($touchUser, $shareCode, $reqTime)
    {
        list($openId, $shareUserId, $inviteId, $shareId, $timestemp, $isAward, $param) = explode('^', $shareCode);
        $activityId = $position = null;
        if ($param) {
            list($type) = explode('|',$param);
            switch ($type) {
                case 1:
                    list(,$flowerId) = explode('|',$param);
                    if ($shareId == GameConst::CULTIVATE_SHARE_ID) {
                        $landId = 21030001; // 暂时固定值  后期修改
                        $userLandList = SzPersister::get()->getVoList($shareUserId, GameConst::ORM_NAME_NEW_CULTIVATE_LAND);
                        $userLand = $userLandList->getElement($landId);
                        /**
                         * @var NewCultivateLandVo $userLand
                         */
                        if ($userLand->getFlowerId() != $flowerId || $userLand->getHarvestTime() < $reqTime) {
                            return true;
                        }
                        $shareCode = $shareId;
                    }
                    break;
                case 2:
                    list(,$activityId,$position) =  explode('|',$param);
                    break;
                case 3:
                    break;
                default:
                    break;
            }

        }

        if ($touchUser == $shareUserId) {
            return false;
        }



        /**
         * @var $shareList ShareVoList
         * @var $share ShareVo
         */
        $shareList = SzPersister::get()->getVoList($shareUserId, GameConst::ORM_NAME_SHARE);
        // 培育分享
        $share = $shareList->getElement($shareCode,false);
        if (!$share) {
            return false;
        }
        $shareId = $share->getShareId();
        $shareConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SHARE, $shareId, true);
        if ($share->getShareTime() + $shareConfig['fx_validity'] < $reqTime) {
            return false;
        }

        //zhangpeng 20200305  特殊处理培育分享（分享当天有效）
        if ($shareId == GameConst::CULTIVATE_SHARE_ID) {
            if (date('ymd',$share->getShareTime()) != date('ymd',$reqTime)) {
                return false;
            }
        }

        $touchUsers = $share->getRawTouchUsers();
        if (in_array($touchUser, $touchUsers)) {
            return false;
        }

        $touchUsers[] = $touchUser;
        if (-1 != $shareConfig['fx_success2Times'] && count($touchUsers) >= $shareConfig['fx_success2Times'] && !$share->getIsGetReward()) {
            foreach ($shareConfig['fx_success2'] as $entityId => $count) {
                GameService::get()->handleEntity($shareUserId, $entityId, $count, true, true);
            }
            $share->setIsGetReward(1);
        }
        if (!empty($shareConfig['fx_success2Visitor'])) {
            foreach ($shareConfig['fx_success2Visitor'] as $entityId => $count) {
                GameService::get()->handleEntity($touchUser, $entityId, $count, true, true);
            }
        }
        $share->setTouchUsers($touchUsers);
        $shareList->updateElement($shareCode, $share);
        SzPersister::get()->setVoList($shareList);
        $this->touchFriendShare($touchUser, $shareUserId, $inviteId,$reqTime);

        if ($shareId == GameConst::INVITE_FRIEND_SHARE_ID) {
            /**
             * @var ModuleProfileVo $profile
             */
            $profile = SzPersister::get()->getVo($touchUser, ModuleProfileConst::ORM_NAME_PROFILE);
            $registerTime = $profile->getRegisterTime();
            if ($reqTime > ($registerTime + 200)) {

            } else {
                NewFriendService::get()->addInviteFriend($shareUserId,$touchUser);
                NewTaskService::get()->updateProgress($shareUserId,GameConst::TASK_INVITE_FRIEND,1);
            }

        }

        if ($shareId == GameConst::INVITE_FRIEND_TRADE_SHARE_ID) {
            //获取交易模块配置
            $gridConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_FRIENDS_DEAL_GRID, 4, true);
            if (!$gridConf || empty($gridConf) || !$gridConf['helpNumber'] || empty($gridConf['helpNumber'])){
                return false;
            }
            /**
             * 获取玩家数据
             * @var $tradeItemList TradeItemVoList
             * @var $tradeItem TradeItemVo
             */
            $tradeItemList = SzPersister::get()->getVoList($shareUserId, GameConst::ORM_NAME_TRADE_ITEM);
            $tradeItem = $tradeItemList->getElement(4,false);
            if (!$tradeItem){
                return false;
            }

            $shareTimes = $tradeItem->getShareTimes();
            $tradeItem->setShareTimes($shareTimes + 1);
            if ($shareTimes + 1 >= $gridConf['helpNumber']){
                $tradeItem->setState(1);
            }

            $tradeItemList->updateElement(4,$tradeItem);
            SzPersister::get()->setVoList($tradeItemList);
        }

        // 数据采集：分享
        StatisticsService::get()->saveLog($touchUser, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:share|action:invite|',
                'item' => $shareId.'&'.$shareUserId,
                'value' => 1,
            )
        ));

        if (is_null($activityId) || is_null($position)) {
            return true;
        }

        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);
        if ($activity) {
            // 分享活动
            $activityInviteSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_INVITE_EVENT, $activityId, true);
            if (!$activityInviteSetting) {
                return true;
            }

            $inviteEventSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_INVITE_EVENT, $activityId, true);
            if (!$inviteEventSetting) {
                return true;
            }

            if ($activity['type'] != 2) {
                return true;
            }

            $startTime = $activity['startTime'];
            if ($startTime > $reqTime) {
                return true;
            }
            $endTime = $activity['endTime'];
            if ($endTime <= $reqTime) {
                return true;
            }

            if ($position > $activityInviteSetting['position']) {
                return true;
            }

            $userActivityShareList = SzPersister::get()->getVoList($activityId.$shareUserId, GameConst::ORM_NAME_ACTIVITY_SHARE);

            if ($userActivityShareList && count($userActivityShareList->toArray()) == $activityInviteSetting['position']) {
                return true;
            }

            $havePosition = array();
            foreach ($userActivityShareList->toArray() as $val) {
                if($val['friendId'] == $touchUser) {
                    return true;
                }
                $havePosition[] = $val['position'];
            }
            if (in_array($position,$havePosition)) {
                $positionList = array();
                for($i=1;$i<=$inviteEventSetting['position'];$i++) {
                    $positionList[] = $i;
                }
                $diff = array_diff($positionList,$havePosition);
                $position = min($diff);
            }

            $userActivityShare = new ActivityShareVo($activityId.$shareUserId,$touchUser, $position, 0,true);
            $userActivityShareList->addElement($userActivityShare);
            $userActivityShareList->setElement($touchUser,$userActivityShare);
            SzPersister::get()->setVoList($userActivityShareList);

            StatisticsService::get()->saveLog($shareUserId, GameConst::LOG_TYPE_USER_ORBIT, array(
                'clientData' => array(
                    'tid' => 'Module:valentine|action:beinvited|',
                    'item' => $touchUser.'&'.$position,
                    'value' => 1
                )
            ));

        }
        return true;
    }

    /**
     * 每次登陆清除过期的链接
     * @param $userId
     * @param $reqTime
     */
    public function dailyClear($userId, $reqTime)
    {
        /**
         * @var $shareList ShareVoList
         * @var $share ShareVo
         */
        $shareList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SHARE);
        $shareConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SHARE, null, true);
        foreach ($shareList->getList() as $shareCode => $share) {
            if ($share->getShareId() != GameConst::CULTIVATE_SHARE_ID) {
                if ($share->getShareTime() + $shareConfig[$share->getShareId()]['fx_validity'] > $reqTime) {
                    continue;
                }
            }else {
                if (date('ymd',$share->getShareTime()) == date('ymd',$reqTime)) {
                    continue;
                }
            }
            
            $shareList->deleteElement($shareCode, false);
        }

        SzPersister::get()->setVoList($shareList);
    }

    /**
     * 点击的分享链接为好友链接
     * @param $touchUserId
     * @param $shareUserId
     * @param $inviteId
     * @return null|int
     */
    public function touchFriendShare($touchUserId, $shareUserId, $inviteId, $reqTime = 0)
    {
        if ($inviteId == -1) {
            return false;
        }

        /**
         * @var ModuleProfileVo $profile
         */
        $profile = SzPersister::get()->getVo($touchUserId, ModuleProfileConst::ORM_NAME_PROFILE);
        if ($reqTime) {
            $registerTime = $profile->getRegisterTime();
            if ($reqTime > ($registerTime + 200)) {
                $inviteId = -1;
            }
        }

        return FriendService::get()->addFriend($touchUserId, $shareUserId, $inviteId);
    }

    public function shareIsExpire($shareConfig,$share,$reqTime) {
        /**
         * @var $share ShareVo
         */
        $shareTime = $share->getShareTime();
        $fx_validity = $shareConfig['fx_validity'];
        if (($shareTime + $fx_validity) >= $reqTime) {
            return false;
        }

        //zhangpeng 20200305  特殊处理培育分享（分享当天有效）
        $shareId = $share->getShareId();
        if ($shareId == GameConst::CULTIVATE_SHARE_ID) {
            if (date('ymd',$shareTime) != date('ymd',$reqTime)) {
                return false;
            }
        }
        return true;
    }
}
